export default class ModelDB {
  constructor(dbName = 'ModelDB', storeName = 'parts') {
    this.dbName = dbName;
    this.storeName = storeName;
    this.db = null;
  }

  /**
   * 打开数据库连接
   * @returns {Promise<IDBDatabase>}
   */
  open() {
    return new Promise((resolve, reject) => {
      if (this.db) {
        resolve(this.db);
        return;
      }

      const request = indexedDB.open(this.dbName, 1);

      request.onerror = (event) => {
        reject(`Database error: ${event.target.error}`);
      };

      request.onsuccess = (event) => {
        this.db = event.target.result;
        resolve(this.db);
      };

      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains(this.storeName)) {
          db.createObjectStore(this.storeName, { keyPath: 'name', autoIncrement: true });
        }
      };
    });
  }

  /**
   * 添加数据
   * @param {Object} data 要添加的数据（不需要包含id）
   * @returns {Promise<number>} 返回自动生成的id
   */
  add(data) {
    return new Promise((resolve, reject) => {
      this.open()
        .then(db => {
          const tx = db.transaction(this.storeName, 'readwrite');
          const store = tx.objectStore(this.storeName);
          // const request = store.add(data);
          const request = store.put(data);

          request.onsuccess = () => resolve(request.result);
          request.onerror = (event) => reject(event.target.error);
        })
        .catch(reject);
    });
  }

  /**
   * 获取数据
   * @param {number} id 数据id
   * @returns {Promise<Object>}
   */
  get(id) {
    return new Promise((resolve, reject) => {
      this.open()
        .then(db => {
          const tx = db.transaction(this.storeName, 'readonly');
          const store = tx.objectStore(this.storeName);
          const request = store.get(id);
          request.onsuccess = () => resolve(request.result);
          request.onerror = (event) => reject(event.target.error);
        })
        .catch(reject);
    });
  }

  /**
   * 更新数据
   * @param {Object} data 要更新的数据（必须包含id）
   * @returns {Promise<void>}
   */
  update(data) {
    return new Promise((resolve, reject) => {
      if (!data.id) {
        reject(new Error('Data must contain an id property'));
        return;
      }

      this.open()
        .then(db => {
          const tx = db.transaction(this.storeName, 'readwrite');
          const store = tx.objectStore(this.storeName);
          const request = store.put(data);

          request.onsuccess = () => resolve();
          request.onerror = (event) => reject(event.target.error);
        })
        .catch(reject);
    });
  }

  /**
   * 删除数据
   * @param {number} id 要删除的数据id
   * @returns {Promise<void>}
   */
  delete(id) {
    return new Promise((resolve, reject) => {
      this.open()
        .then(db => {
          const tx = db.transaction(this.storeName, 'readwrite');
          const store = tx.objectStore(this.storeName);
          const request = store.delete(id);

          request.onsuccess = () => resolve();
          request.onerror = (event) => reject(event.target.error);
        })
        .catch(reject);
    });
  }

  /**
   * 关闭数据库连接
   */
  close() {
    if (this.db) {
      this.db.close();
      this.db = null;
    }
  }
}